#include <stdio.h>
#include "common_list.h"

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode *help = (struct ListNode*)malloc(sizeof(*head));
    help->next = head;
    struct ListNode *fast = help, *slow = help, *tmp;

    while(n-- >= 0 && fast) {
        fast = fast->next;
    }

    while(fast) {
        fast = fast->next;
        slow = slow->next;
    }
    if (slow && slow->next) {
        tmp = slow->next;
        slow->next = slow->next->next;
        free(tmp);
    }
    return help->next;
}

int main(void)
{
    printf("#19. 删除链表的倒数第 N 个结点\n");

    struct ListNode *head = generate_list(1);
    print_list(head);
    head = removeNthFromEnd(head, 1);
    print_list(head);

    return 0;
}